<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>基于 Token 的登录页面</title>
</head>
<body>
  <h2>登录</h2>
  <form id="login-form">
    用户名: <input type="text" id="username" required><br>
    密码: <input type="password" id="password" required><br>
    <button type="submit">登录</button>
  </form>

  <hr>

  <h2>获取游戏列表（需要 token）</h2>
  <button id="fetch-games">查询游戏</button>
  <ul id="game-list"></ul>

  <div id="game-detail" style="margin-top:20px;"></div>

  <script>
    // 登录功能
    document.getElementById('login-form').addEventListener('submit', async function(e) {
      e.preventDefault();

      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;

      const response = await fetch('http://127.0.0.1:8080/casedemo15/login/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      const result = await response.json();

      if (response.ok) {
        localStorage.setItem('token', result.token);
        alert('登录成功，token 已保存');
      } else {
        alert(result.msg || '登录失败');
      }
    });

    // 获取游戏列表
    document.getElementById('fetch-games').addEventListener('click', async function() {
      const token = localStorage.getItem('token');
      if (!token) {
        alert('请先登录');
        return;
      }

      const response = await fetch('http://127.0.0.1:8080/casedemo15/games/', {
        method: 'GET',
        headers: {
          'Authorization': 'Token ' + token
        }
      });

      if (!response.ok) {
        alert(response.statusText);
        alert("获取失败，可能是 token 失效或无权限");
        return;
      }

      const data = await response.json();
      const gameList = document.getElementById('game-list');
      gameList.innerHTML = '';

      data.forEach(game => {
        const li = document.createElement('li');
        li.innerHTML = `
          游戏名：${game.name}，描述：${game.desc}
          <button onclick="viewGame(${game.id})">查看</button>
          <button onclick="editGame(${game.id})">修改</button>
          <button onclick="deleteGame(${game.id})">删除</button>
        `;
        gameList.appendChild(li);
      });
    });

    // 查看游戏详情
    async function viewGame(id) {
      const token = localStorage.getItem('token');
      const response = await fetch(`http://127.0.0.1:8080/casedemo15/games/${id}/`, {
        method: 'GET',
        headers: {
          'Authorization': 'Token ' + token
        }
      });

      if (!response.ok) {
        alert('获取详情失败');
        return;
      }

      const data = await response.json();

      document.getElementById('game-detail').innerHTML = `
        <h3>游戏详情</h3>
        <p>游戏名：<input type="text" id="edit-name" value="${data.name}"></p>
        <p>描述：<input type="text" id="edit-desc" value="${data.desc}"></p>
        <button onclick="saveGame(${data.id})">保存修改</button>
      `;
    }

    // 修改游戏
    async function saveGame(id) {
      const token = localStorage.getItem('token');
      const name = document.getElementById('edit-name').value;
      const desc = document.getElementById('edit-desc').value;

      const response = await fetch(`http://127.0.0.1:8080/casedemo15/games/${id}/`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Token ' + token
        },
        body: JSON.stringify({ name, desc })
      });

      if (response.ok) {
        alert('修改成功');
        location.reload();
      } else {
        alert('修改失败');
      }
    }

    // 删除游戏
    async function deleteGame(id) {
      if (!confirm('确定要删除该游戏吗？')) return;

      const token = localStorage.getItem('token');
      const response = await fetch(`http://127.0.0.1:8080/casedemo15/games/${id}/`, {
        method: 'DELETE',
        headers: {
          'Authorization': 'Token ' + token
        }
      });

      if (response.ok) {
        alert('删除成功');
        location.reload();
      } else {
        alert('删除失败');
      }
    }
  </script>
</body>
</html>
